import { defineStore } from "pinia";

import {
    getDeviceApi,
    addDeviceApi,
    updateDeviceApi,
    delDeviceApi,
    exportAllDataApi,
    getDeviceThresholdApi,
    updateDeviceThresholdApi,
    updateDeviceVideodApi,
    updateDeviceVersionApi,
    downloadModelApi,
    uploadModelApi
} from '@/Api/Device'
import EventBus from "@/utils/EventBus";
import { downloadFileData } from "@/utils/downloadFile";

import { useCommon } from "./Common";

const CommonStore = useCommon()
const isDev = import.meta.env.MODE == 'development'


export const useDevice = defineStore('Device', {
    state: (): DeviceState => {
        return {
            showMore: false,
            isOver: false,
            searchForm: {
                serial: '',
                deviceName: '',
                area: '',
                principal: '',
                state: null,
                department: '',
                illArea: '',
                departmentWard: [],

                pageNo: 1,
                pageSize: 10,
                total: 0,
                showSizeChanger: true,
                pageSizeOptions: ['10', '20', '30', '50'],
                showTotal() { },
                onChange() { }
            },
            addForm: {} as Device,
            editForm: {} as Device,
            tableData: [],
            thresholdInfo: {
                disinfectData: "",
                tubeCount: "",
                alarmData: "",
                alarmCount: "",
                lockData: "",
            },
            videoForm: {
                serials: [],
                file: []
            },
            versionForm: {
                serials: [],
                versionUrl: ''
            },
            modelForm: {
                multipartFile: []
            },
        }
    },
    actions: {
        async getDevice() {
            if (this.searchForm.departmentWard != undefined && this.searchForm.departmentWard.length == 1) {
                this.searchForm.department = this.searchForm.departmentWard[0]
                this.searchForm.illArea = null
            } else if (this.searchForm.departmentWard != undefined && this.searchForm.departmentWard.length == 2) {
                this.searchForm.department = this.searchForm.departmentWard[0]
                this.searchForm.illArea = this.searchForm.departmentWard[1]
            } else {
                if (CommonStore.department != '检验科') {
                    this.searchForm.department = CommonStore.department
                    this.searchForm.illArea = CommonStore.illArea
                } else {
                    this.searchForm.department = ''
                    this.searchForm.illArea = ''
                }
            }
            console.log(this.searchForm.pageSize, this.searchForm.pageNo);

            const data = await getDeviceApi(this.searchForm) as any
            if (data) {
                this.tableData = data[0]
                this.tableData.forEach((item: Device, index) => {
                    item.departmentName = item.illArea ? `${item.department}-${item.illArea}` : `${item.department}`
                    item.departmentWard = item.illArea ? [item.department, item.illArea] : [item.department]
                    item.videoName = item.videoUrl?.split('/').pop()!
                })
                this.searchForm.total = data[1][0].total
            }
        },
        async loadMoreData() {
            console.log('加载更多数据');


            this.searchForm.pageNo += 1
            const data = await getDeviceApi(this.searchForm) as any
            if (data[0].length) {
                data[0].forEach((item: any, index: number) => {
                    item.departmentName = item.illArea ? `${item.department}-${item.illArea}` : `${item.department}`
                    item.departmentWard = item.illArea ? [item.department, item.illArea] : [item.department]
                    item.videoName = item.videoUrl?.split('/').pop()!
                })
                this.tableData.push(...data[0])
                if (this.tableData.length == data[1][0].total) {
                    this.isOver = true
                }
            }
            this.showMore = false
        },
        async addDevice() {
            const data = await addDeviceApi(this.addForm)

            if (!data) {
                this.searchForm.pageNo = 1
                this.searchForm.pageSize = this.searchForm.total + 1
                EventBus.emit('AddSuccess')
                this.getDevice()
                CommonStore.getAllDevice()
            }
        },
        async editDevice() {
            this.editForm.department = this.editForm.departmentWard[0]
            this.editForm.illArea = this.editForm.departmentWard[1]
            const data = await updateDeviceApi(this.editForm)

            if (!data) {
                this.searchForm.pageNo = 1
                this.searchForm.pageSize = this.searchForm.total
                this.getDevice()
                CommonStore.getAllDevice()
                EventBus.emit('UpdateSuccess')
            }
        },
        async delDevice(id: number) {
            const data = await delDeviceApi({ id })

            if (!data) {
                this.searchForm.pageNo = 1
                this.searchForm.pageSize = this.searchForm.total
                this.getDevice()
                EventBus.emit('DeleteSuccess')
            }
        },
        async exportAllData() {
            const data = await exportAllDataApi({
                department: CommonStore.department == '检验科' ? '' : CommonStore.department,
                illArea: CommonStore.illArea
            })
            if (data) {
                downloadFileData(data, "设备管理数据.xlsx")
            }
        },
        async getThreshold(serial: string) {
            const data = await getDeviceThresholdApi({
                pageNo: 1,
                pageSize: 1,
                serial
            }) as any
            if (data[0][0]) {
                this.thresholdInfo = data[0][0]
            }
        },
        async updateThreshold() {
            const data = await updateDeviceThresholdApi(this.thresholdInfo) as any
            if (!data) {
                EventBus.emit('UpdateSuccess')
                this.getDevice()
            }
        },
        async setVideo() {
            const formData = new FormData()
            for (const key in this.videoForm) {
                if (key == 'file') {
                    formData.append(key, this.videoForm[key][0])
                } else if (key == 'serials') {
                    formData.append(key, this.videoForm[key].join(','))
                }
            }
            try {
                const data = await updateDeviceVideodApi(formData,) as any
                if (!data) {
                    EventBus.emit('UploadSuccess')
                    this.getDevice()
                }
            } finally { }
        },
        async ctrlVersion() {
            const formData = new FormData()
            for (const key in this.versionForm) {
                if (key == 'versionUrl') {
                    formData.append(key, this.versionForm[key])
                } else if (key == 'serials') {
                    formData.append(key, this.versionForm[key].join(','))
                }
            }
            try {
                const data = await updateDeviceVersionApi(formData) as any
                console.log(data);

                if (!data) {
                    EventBus.emit('UpdateSuccess')
                    this.getDevice()
                }
            } finally { }
        },
        // 下载模板
        async downloadModel() {
            // const data = await downloadModelApi() as any
            const data = await (await fetch(isDev ? '/设备模板.xlsx' : "/closet/设备模板.xlsx")).blob()
            if (data) {
                downloadFileData(data, "设备模板.xlsx")
            }
        },
        // 上传数据
        async uploadModel() {
            const formData = new FormData()
            for (const key in this.modelForm) {
                if (key == 'multipartFile') {
                    formData.append(key, this.modelForm[key][0])
                }
            }
            try {
                const data = await uploadModelApi(formData) as any
                if (data) {
                    downloadFileData(data, "设备模板注册情况.xlsx")
                    EventBus.emit('UploadSuccess')
                    this.getDevice()
                }
            } finally { }
        },
    }
})